package com.yjd.merchant.api.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjd.comm.enums.ApiRequestWayEnum;
import com.yjd.comm.user.dto.MerchantSession;
import com.yjd.comm.util.*;
import com.yjd.comm.vo.CachedKeys;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

/**
 * 加密/解密处理
 * Created by yangchangyan on 2017/12/4.
 */
public class EncryptionFilter implements Filter {

    Logger log = Logger.getLogger(EncryptionFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);

        filterChain.doFilter(servletRequest, responseWrapper);

        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            //取返回的json串
            JSONObject data = JSON.parseObject(responseWrapper.getResult());
            // 是否加密 0否 1是
            data.put("encryption", "0");

            // 只对APP的请求进行加密
            String api_request_way = servletRequest.getParameter("api_request_way");
            if(StringUtil.isNotEmpty(api_request_way) && ApiRequestWayEnum.APP.getValue().toString().equals(api_request_way.trim())){
                // 判断有没有在不需要登陆列表中，不需要登陆的接口不加密
                if (urlIsNeedValidate(ServletUtil.getRquestUriNotContainContextPath((HttpServletRequest)servletRequest))) {
                    MerchantSession merchantSession = (MerchantSession)servletRequest.getAttribute(CachedKeys.MERCHANT_USER);
                    if(null != merchantSession){
                        String content = CryptAES.AES_Encrypt(SecurityCode.md5(merchantSession.getDevice_no()), JSON.toJSONString(data.get("data")));
                        data.put("data", content);
                        data.put("encryption", "1");
                    }
                }
            }
            out.write(data.toJSONString());
        } finally {
            out.flush();
            out.close();
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * @Title: urlIsNeedValidate
     * @Description: 判断url是否需要验证
     * @param @param requestUrl
     * @param @return 设定文件
     * @return boolean 返回类型
     * @throws
     */
    protected boolean urlIsNeedValidate(String requestUrl) {
        return !FrameUtil.isValidate(FrameUtil.newArrayList("nologinurl.txt"), requestUrl);
    }

    class ResponseWrapper extends HttpServletResponseWrapper {
        private PrintWriter cachedWriter;
        private CharArrayWriter bufferedWriter;

        public ResponseWrapper(HttpServletResponse response) throws IOException {
            super(response);
            bufferedWriter = new CharArrayWriter();
            cachedWriter = new PrintWriter(bufferedWriter);
        }

        public PrintWriter getWriter() throws IOException {
            return cachedWriter;
        }

        public String getResult() {
            try {
                byte[] bytes = bufferedWriter.toString().getBytes("UTF-8");
                return new String(bytes, "UTF-8");
            } catch (Exception e) {
                log.error("EncryptionFilter error:",e);
                return "";
            }
        }
    }
}
